//
//  MPNetworkConfig.m
//  MPHttpRequest
//
//  Created by yafei liu on 2021/4/20.
//

#import "MPNetworkConfig.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation MPNetworkConfig

+ (instancetype)sharedManager{
    static MPNetworkConfig *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
//        NSString *string_content = [[NSString alloc] initWithCString:(const unsigned char*)MPHttpRequestVersionString
//        encoding:NSASCIIStringEncoding];
#ifdef DEBUG
    NSLog(@"当前SDK版本号：%@",[MPNetworkConfig SDKVersion]);
#else
#endif
    });
    return sharedInstance;
}

+(NSString *)SDKVersion{
    return @"1.0.0";
}
 
/*
 +(NSURLSessionTask *)POST1:(NSString *)URL parameters:(id)parameters success:(MPHttpRequestSuccess)success failure:(MPHttpRequestFailed)failure{
 NSString *requestPath = @"/user-center/userBasic/query/page";
 NSString *access_token = @"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXV0aC1zZXJ2aWNlIiwidXNlci1jZW50ZXIiLCJzdXBwbGllci13ZWIiXSwidXNlcl9uYW1lIjoic3VwcGxpZXItd2ViIiwic2NvcGUiOlsiYWxsIl0sInVzZXJCYXNpYyI6eyJpZCI6MTYsInVzZXJOYW1lIjoic3VwcGxpZXItd2ViIiwiZ2VuZGVyIjpudWxsLCJtb2JpbGUiOiIxNTI2NjU1Nzg1MyIsImZpeGVkUGhvbmUiOm51bGx9LCJjb21wYW55Ijoid3d3LmxhbmNldC5jb20uY24iLCJleHAiOjE2MTkwMTMwNzQsIm1lc3NhZ2UiOiLorqTor4HmiJDlip8iLCJhdXRob3JpdGllcyI6WyIvdXNlci1jZW50ZXIvKioiLCIvc3VwcGxpZXItd2ViLyoqIiwiL2F1dGgtc2VydmljZS8qKiJdLCJqdGkiOiJhNzFhNWM1Yi01YzIyLTQyYmItYmNlZi05NGJkZGYwMWVkMWYiLCJjbGllbnRfaWQiOiJzdXBwbGllci13ZWItYXBwIn0.mg6W9vXmaGOMhvfWSl4khnvqB7zFYmqYQaqCBUpfntA";
 [MPNetworkHelper openLog];
 [MPNetworkHelper setRequestSerializer:MPRequestSerializerJSON];
 //    [MPNetworkHelper setValue:@"access_token" forHTTPHeaderField:access_token];
 
 NSArray *paramsKeys = [[(NSDictionary *)parameters allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
 return [obj1 compare:obj2];
 }];
 NSMutableArray *mutArray = [NSMutableArray array];
 for (NSString *key in paramsKeys) {
 NSString *keyValue = [[NSString alloc] initWithFormat:@"%@=%@",key,[parameters objectForKey:key]];
 [mutArray addObject:keyValue];
 }
 NSString *sortStr = [mutArray componentsJoinedByString:@"&"];
 
 NSMutableString *mutStr = [NSMutableString string];
 NSString *clientId = @"supplier-web-app";
 //    NSString *curTime = [NSString stringWithFormat:@"%.0lf",[[NSDate date] timeIntervalSince1970]*1000];
 NSString *curTime = @"1618911757578";
 [mutStr appendString:requestPath];
 NSString *jsonToString = [MPNetworkConfig jsonToString:parameters];
 //    NSString *jsonToString = @"{\"current\":1,\"pageSize\":2}";
 NSString *paramStr = [@"requestBody=" stringByAppendingString:jsonToString];
 [mutStr appendString:paramStr];
 
 //    [mutStr appendString:sortStr];
 [mutStr appendString:@"supplier-web-app"];
 [mutStr appendString:curTime];
 
 NSString *md5Str = [MPNetworkConfig md5StringWithStr:mutStr];
 [MPNetworkHelper setValue:md5Str forHTTPHeaderField:@"Sign-Key"];
 [MPNetworkHelper setValue:curTime forHTTPHeaderField:@"Cur-Time"];
 NSString *authorization = [@"bearer " stringByAppendingString:access_token];
 [MPNetworkHelper setValue:authorization forHTTPHeaderField:@"Authorization"];
 
 NSMutableDictionary *mutableParams = [NSMutableDictionary dictionary];
 [mutableParams setObject:curTime forKey:@"curTime"];
 //    [mutableParams setObject:parameters forKey:@"params"];
 [mutableParams setObject:jsonToString forKey:@"requestBodyStr"];
 [mutableParams setObject:@"{\"current\":1,\"pageSize\":2}" forKey:@"requestBodyStr"];
 
 [mutableParams setObject:requestPath forKey:@"requestPath"];
 
 NSURLSessionTask * task = [MPNetworkHelper POST:URL parameters:parameters headers:nil success:^(id responseObject) {
 //        {
 //            msg = 成功;
 //            data = {
 //            loginCode = DOML;
 //            grantServerList = <null>;
 //        }
 //        ;
 //            code = 0;
 //        }
 if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
 NSNumber *codeNumber = [responseObject objectForKey:@"code"];
 NSInteger code = codeNumber.integerValue;
 if (code == 0) {
 NSString *loginCode = [responseObject objectForKey:@"loginCode"];
 if (loginCode) {
 
 }
 if (success) {
 success(responseObject);
 }
 return;
 }
 }
 if (failure) {
 NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:responseObject[@"msg"],NSLocalizedDescriptionKey,@"ServerError",NSLocalizedFailureReasonErrorKey, nil];
 NSString *str = responseObject[@"msg"];
 str = str.length > 0 ? str : @"未知错误";
 NSError * error = [NSError errorWithDomain:str code:[responseObject[@"code"] integerValue] userInfo:info];
 failure(error);
 }
 } failure:^(NSError *error) {
 if (failure) {
 failure(error);
 }
 }];
 NSLog(@"\n请求URL:%@\n请求方式:%@\n请求头信息:%@\n",task.originalRequest.URL,task.originalRequest.HTTPMethod,task.originalRequest.allHTTPHeaderFields);
 NSLog(@"请求正文信息:%@\n\n",[[NSString alloc] initWithData:task.originalRequest.HTTPBody encoding:NSUTF8StringEncoding]);
 
 return task;
 }
 */

+ (NSString *)jsonStringWithObject:(id)data {
    if(data == nil) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingFragmentsAllowed error:nil];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (NSString *)md5StringWithStr:(NSString *)str {
    return [self md5StringWithData:[str dataUsingEncoding:NSUTF8StringEncoding]];
}

+ (NSString *)md5StringWithData:(NSData *)data {
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, (CC_LONG)data.length, result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

@end
